<template>
  <div class="designer-form flex flex-col justify-between h-full">
    <el-form
      ref="registerFormRef"
      :model="ruleForm"
      :rules="rules"
      label-width="0px"
      :size="formSize"
      status-icon
    >
      <el-form-item label=" " prop="nickname" required class="form-width">
        <el-input v-model="ruleForm.nickname" placeholder="请输入姓名" class="input-height" />
      </el-form-item>
      <el-form-item
        label=""
        prop="userType"
        required
        label-position="right"
        class="form-width border-0"
      >
        <el-select
          v-model="ruleForm.userType"
          placeholder="设计师或项目经理"
          clearable
          class="input-height"
          @change="handleChangeMode"
        >
          <el-option
            v-for="item in userTypeList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label=" " prop="phonenumber" required class="form-width">
        <el-input
          v-model="ruleForm.phonenumber"
          placeholder="请输入手机号"
          maxlength="11"
          class="input-height"
        />
      </el-form-item>
      <el-form-item label=" " prop="code" class="form-width">
        <el-input v-model="ruleForm.code" placeholder="验证码" class="login-input h-[48px]">
          <template #append>
            <CodeButton
              :mobile="ruleForm.phonenumber"
              smsType="REGISTER"
              :validateFunction="validateFunction"
              @getCode="(code) => (ruleForm.code = code)"
            />
          </template>
        </el-input>
      </el-form-item>
      <!-- <div class="form-section flex justify-between">
        <el-form-item label="" prop="idCardFrontFile" class="mutiple-upload border-0 form-width">
          <MultiImageUpload
            v-model="ruleForm.idCardFrontFile"
            :limit="1"
            @uploadSuccess="handleCardFrontFile"
          >
            <template #default>
              <img src="@/assets/images/idcard_back.png" class="upload-img" />

              <div class="flex justify-center items-center absolute">
                <el-link type="primary" @click="handleUploadIdCardBackFile">点击上传</el-link>
                <span>人像面</span>
              </div>
            </template>
          </MultiImageUpload>
        </el-form-item>
        <el-form-item label="" prop="idCardBackFile" class="mutiple-upload border-0 form-width">
          <MultiImageUpload
            v-model="ruleForm.idCardBackFile"
            :limit="1"
            @uploadSuccess="handleCardBackFile"
          >
            <template #default>
              <img src="@/assets/images/idcard_front.png" class="upload-img" />

              <div class="flex justify-center items-center absolute">
                <el-link type="primary" @click="handleUploadIdCardBackFile">点击上传</el-link>
                <span>国徽面</span>
              </div>
            </template>
          </MultiImageUpload>
        </el-form-item>
      </div>
      <div class="form-section flex justify-between">
        <el-form-item label=" " prop="idNumber" required class="form-width">
          <el-input
            v-model="ruleForm.idNumber"
            placeholder="请输入身份证号码"
            class="input-height"
          />
        </el-form-item>
        <el-form-item label="" required prop="idCardValidity" class="form-width border-0">
          <el-date-picker
            v-model="ruleForm.idCardValidity"
            type="daterange"
            start-placeholder="有效期"
            end-placeholder="自动识别身份证"
            value-format="YYYYMMDD"
            class="input-height"
          />
        </el-form-item>
      </div> -->
      <!-- <el-form-item
        label=""
        prop="mallName"
        required
        :class="activeMallMode === 'SELECT' ? 'border-0' : 'border-0'"
      >
        <div class="mall-select-wrapper flex form-width">
          <template v-if="activeMallMode === 'SELECT'">
            <el-select
              v-model="ruleForm.mallNameId"
              placeholder="所在商圈/商场"
              clearable
              class="input-height w-full"
              @change="
                () => {
                  ruleForm.mallName = mallList.find(
                    (item) => item.id === ruleForm.mallNameId
                  )?.mallName;
                }
              "
            >
              <el-option
                v-for="item in mallList"
                :key="item.id"
                :label="item.mallName"
                :value="item.id"
              />
            </el-select>
          </template>
          <template v-else>
            <el-input
              v-model="ruleForm.mallName"
              placeholder="所在商圈/商场"
              class="input-height border-1 pl-2"
            />
          </template>
        </div>
        <el-button style="margin-left: 3%" type="primary" link @click="changeMallMode">
          {{ mallChangeTitle }}
        </el-button>
      </el-form-item> -->
    </el-form>
    <RegisterButton
      class="mt-10"
      :loading="loading"
      @submit="submitForm"
      @register="emit('register')"
    />
    <Summary ref="summaryRef" @confirm="handleConfirm" @cancel="handleCancel"></Summary>
  </div>
</template>

<script setup>
import RegisterButton from "../components/RegisterButton.vue";
import CodeButton from "@/components/SmsCode/CodeButton.vue";
import { addMerchantEmployee } from "@/api/register/index";
import { getIdCardFaceInfo, getIdCardBackInfo } from "@/api/system/common";
import { getMallList } from "@/api/myIndex/index";
// 组件
import { validateIdCard, validatePhone } from "@/utils/formvalidate";
import { SYSTEM_TYPE_REVERSE_OBJECT, SYSTEM_TYPE_LIST } from "@/utils/enums/system";
import Summary from "@/views/login/components/summary.vue";

const emit = defineEmits(["registerSuccess", "register"]);
const registerFormRef = ref();
const validateFunction = async (mobile) => {
  console.log(mobile);
  const result = await registerFormRef.value?.validateField("mobile", (valid) => {
    if (valid) {
      console.log("valid");
      return true;
    } else {
      ElMessage.error("请输入有效的手机号码");
      return false;
    }
  });
  console.log(result);
  return result;
};
// 主体类型列表
const userTypeList = computed(() => {
  const isSelfRegister = [
    SYSTEM_TYPE_REVERSE_OBJECT["设计师"],
    SYSTEM_TYPE_REVERSE_OBJECT["项目经理"],
  ];
  console.log(isSelfRegister);

  let list = SYSTEM_TYPE_LIST.filter((item) => isSelfRegister.includes(item.value));
  console.log(list, "list");
  return list;
});
const formSize = ref("default");
const summaryRef = ref();
const isAgree = ref(false);
/***
 * 表单校验管理
 *
 */

const ruleForm = reactive({
  nickname: "",
  phonenumber: "",
  code: "",
  idNumber: "",
  idCardValidity: "",
  idCardFrontFile: [],
  idCardBackFile: [],
});
// 上传图片统一处理
const handleCardFrontFile = () => {
  identifyFaceCard();
};
const handleCardBackFile = () => {
  identifyBackCard();
};

const rules = reactive({
  // mallName: [{ required: true, message: "请选择或者填写商圈/商场", trigger: "blur" }],
  nickname: [
    { required: true, message: "请输入姓名", trigger: "blur" },
    { min: 2, max: 20, message: "姓名长度应在2-20个字符之间", trigger: "blur" },
  ],
  userType: [{ required: true, message: "设计师或项目经理不能为空", trigger: "change" }],
  phonenumber: [
    { required: true, message: "请输入手机号", trigger: "blur" },
    { validator: validatePhone, trigger: "blur" },
  ],
  idNumber: [
    { required: true, message: "请输入身份证号码", trigger: "blur" },
    { validator: validateIdCard, trigger: "blur" },
  ],
  // idCardValidity: [{ required: true, message: "请选择身份证有效期限", trigger: "blur" }],
  // idCardFrontFile: [{ required: true, message: "请上传身份证正面图片", trigger: "blur" }],
  // idCardBackFile: [{ required: true, message: "请上传身份证反面图片", trigger: "blur" }],
});

/**
 *  所在商圈/商场 处理
 *
 */
const mallList = ref([]);
// SELECT 和 INPUT 模式
const activeMallMode = ref("SELECT");
const mallChangeTitle = ref("手动填写");
const changeMallMode = () => {
  // 清空商圈选中的值
  ruleForm.mallNameId = "";
  ruleForm.mallName = "";
  activeMallMode.value = activeMallMode.value === "SELECT" ? "INPUT" : "SELECT";
  mallChangeTitle.value = activeMallMode.value === "SELECT" ? "手动填写" : "选择商圈";
};
async function funcGetMallList() {
  try {
    const data = await getMallList();
    mallList.value = data.data;
  } catch (err) {
    console.log(err);
  }
}
const handleConfirm = () => {
  isAgree.value = true;
  // return ElMessage.success("申请入驻成功，请登录");
  handleAddMerchantEmployee({
    ...ruleForm,
    subjectType: "21", // 个人
    // idCardValidity: ruleForm.idCardValidity.join(","),
    // idCardBackFile: JSON.stringify(ruleForm.idCardBackFile),
    // idCardFrontFile: JSON.stringify(ruleForm.idCardFrontFile),
  });
};
const handleCancel = () => {
  isAgree.value = false;
};

const submitForm = async () => {
  await registerFormRef.value?.validate((valid, fields) => {
    if (valid) {
      if (!isAgree.value) {
        summaryRef.value.showModal();
      } else {
        handleAddMerchantEmployee({
          ...ruleForm,
          subjectType: "21", // 个人
          // idCardValidity: ruleForm.idCardValidity.join(","),
          // idCardBackFile: JSON.stringify(ruleForm.idCardBackFile),
          // idCardFrontFile: JSON.stringify(ruleForm.idCardFrontFile),
        });
      }
    } else {
      console.log("error submit!", fields);
    }
  });
};

const handleAddMerchantEmployee = async (params) => {
  try {
    console.log(params, "params");
    await addMerchantEmployee(params);
    ElMessage.success("申请入驻成功，请登录");
    emit("registerSuccess");
  } catch (err) {
    console.log(err);
  }
};
const handleChangeMode = () => {
  console.log("handleChangeMode");
};
/**
 * ocr 识别
 *
 *
 */
// 身份证正面
const identifyFaceCard = async () => {
  try {
    const data = await getIdCardFaceInfo({
      url: ruleForm?.idCardFrontFile[0]?.url,
    });
    ruleForm.legalRepresentative = data.data.name;
    ruleForm.idNumber = data.data.num;
  } catch (err) {
    console.log(err);
  }
};
// 身份证反面
const identifyBackCard = async () => {
  try {
    const data = await getIdCardBackInfo({
      url: ruleForm?.idCardBackFile[0]?.url,
    });
    ruleForm.idCardValidity = [data.data.startDate, data.data.endDate];
  } catch (err) {
    console.log(err);
  }
};
onMounted(() => {
  // funcGetMallList();
});
</script>

<style lang="scss" scoped>
.designer-form {
  width: 100%;
  height: 100%;
  // .form-width {
  //   width: 48%;
  // }
  :deep(.input-height) {
    height: 48px !important;
    .el-select__wrapper {
      height: 100% !important;
    }
  }
  .border-0 {
    border: 0 !important;
  }
  .border-1 {
    border: 1px solid #dcdfe6 !important;
  }
  .mutiple-upload {
    :deep(.el-form-item__content) {
      .el-upload-list--picture-card .el-upload-list__item {
        width: 100% !important;
      }
      // width: 100% !important;
      .el-upload {
        width: 100% !important;
        .upload-img {
          width: 100% !important;
        }
      }
    }
  }
  .bottom-button {
    width: 70% !important;
    margin: 0 auto !important;
  }

  //从登录挪过来的
  :deep(.el-form-item) {
    background: var(--el-input-bg-color);
    border: 1px solid var(--el-border-color);
    border-radius: 5px;
  }

  :deep(.el-input) {
    .el-input__wrapper {
      padding: 0;
      background-color: transparent;
      box-shadow: none;

      &.is-focus,
      &:hover {
        box-shadow: none !important;
      }

      input:-webkit-autofill {
        /* 通过延时渲染背景色变相去除背景颜色 */
        transition: background-color 1000s ease-in-out 0s;
      }
    }
  }
}
</style>
